<template>
  <view class="order">
    <!-- 顶部标签导航栏 -->
    <view class="tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab-item"
        :class="{ active: currentTab === index }"
        @tap="handleTabChange(index)"
      >
        <text>{{ tab }}</text>
        <!-- 活动标签下的指示线 -->
        <view v-if="currentTab === index" class="active-line"></view>
      </view>
    </view>

    <!-- 订单列表区域 -->
    <view class="order-list" v-if="orders.length">
      <!-- 单个订单卡片 -->
      <view class="order-item" v-for="order in orders" :key="order.order_id">
        <!-- 订单头部信息：类型和状态 -->
        <view class="order-header">
          <view class="shop-info">
            <!-- 订单类型标签：堂食/外卖 -->
            <text class="tag">{{ order.order_type === 1 ? '堂食' : '外卖' }}</text>
            <!-- 根据订单类型显示餐桌号或配送地址 -->
            <text class="shop-name" v-if="order.order_type === 1">{{ order.board_name }}</text>
            <text class="shop-name" v-else>{{ order.shipping_address }}</text>
          </view>
          <!-- 订单状态：已支付/待支付/已取消 -->
          <text class="status">{{ getOrderStatus(order.order_status) }}</text>
        </view>

        <!-- 订单下单时间 -->
        <view class="order-time">下单时间：{{ formatTime(order.place_order_time) }}</view>

        <!-- 订单商品列表，根据展开状态显示全部或第一个 -->
        <view class="order-content" v-for="item in getVisibleItems(order)" :key="item.item_id">
          <image 
            class="product-image" 
            :src="item.dish_image ? `https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${item.dish_image}` : '/static/mine/search.png'" 
            mode="aspectFill" 
          />
          <view class="product-info">
            <text class="product-name">{{ item.dish_name }}</text>
            <view class="product-meta">
              <text class="count">x{{ item.quantity }}</text>
            </view>
          </view>
          <view class="price">¥{{ item.price * item.quantity }}</view>
        </view>

        <!-- 展开/收起按钮，仅在有多个商品时显示 -->
        <view v-if="order.items && order.items.length > 1" class="expand-btn" @tap="toggleExpand(order.order_id)">
          <text>{{ isExpanded(order.order_id) ? '收起' : `展开更多 ${order.items.length - 1} 个商品` }}</text>0
          <text class="expand-icon" :class="{ 'is-expanded': isExpanded(order.order_id) }">></text>
        </view>

        <!-- 订单金额信息 -->
        <view class="order-footer">
          <view class="amount-info">
            <text>总计：</text>
            <text class="total-amount">¥{{ order.total_amount }}</text>
            <!-- 优惠金额，仅在有优惠时显示 -->
            <text class="discount" v-if="order.discount_amount > 0">
              (优惠：¥{{ order.discount_amount }})
            </text>
          </view>
          <text class="payable-amount">实付：¥{{ order.payable_amount }}</text>
        </view>

        <!-- 订单操作按钮 -->
        <view class="order-actions">
          <!-- 未支付的堂食订单显示支付按钮 -->
          <template v-if="order.order_type === 1 && order.order_status === 1">
            <button 
              class="action-btn" 
              @tap="addMoreDishes(order.order_id)"
            >继续加菜</button>
            <button 
              class="action-btn primary"
              @tap="payOrder(order.order_id)"
            >立即支付</button>
          </template>

          <!-- 其他情况显示查看订单详情按钮 -->
          <template v-else>
            <button 
              class="action-btn primary"
              @tap="viewOrderDetail(order.order_id)"
            >查看订单详情</button>
          </template>
        </view>
      </view>
      
      <!-- 底部加载更多 -->
      <u-loadmore
        :status="loadMoreStatus"
        @loadmore="loadMore"
        loading-text="努力加载中"
        loadmore-text="点击或上拉加载更多"
        nomore-text="没有更多了"
      />
    </view>

    <!-- 空状态展示 -->
    <view class="empty-state" v-else>
      <image class="empty-icon" src="/static/mine/search.png" mode="aspectFit" />
      <text class="empty-text">您暂时还没有订单呢~</text>
      <button class="order-btn" @tap="goToOrder">去点单</button>
    </view>

    <!-- 订单详情弹窗 -->
    <view class="modal" v-if="showOrderDetail">
      <view class="modal-mask" @tap="closeOrderDetail"></view>
      <view class="order-detail-popup">
        <view class="popup-header">
          <text class="title">订单详情</text>
          <text class="close-btn" @tap="closeOrderDetail">×</text>
        </view>
        
        <scroll-view scroll-y class="popup-content">
          <template v-if="currentOrder">
            <!-- 订单基本信息 -->
            <view class="detail-section">
              <view class="section-title">基本信息</view>
              <view class="info-item">
                <text class="label">订单编号：</text>
                <text class="value">{{ currentOrder.order_id }}</text>
              </view>
              <view class="info-item">
                <text class="label">订单类型：</text>
                <text class="value">{{ currentOrder.order_type === 1 ? '堂食' : '外卖' }}</text>
              </view>
              <view class="info-item">
                <text class="label">下单时间：</text>
                <text class="value">{{ currentOrder.place_order_time }}</text>
              </view>
              <view class="info-item">
                <text class="label">订单状态：</text>
                <text class="value">{{ getOrderStatus(currentOrder.order_status) }}</text>
              </view>
            </view>

            <!-- 订单商品信息 -->
            <view class="detail-section">
              <view class="section-title">商品信息</view>
              <view class="product-list">
                <view class="product-item" v-for="item in currentOrder.items" :key="item.item_id">
                  <view class="product-info">
                    <text class="name">{{ item.dish_name }}</text>
                    <text class="quantity">x{{ item.quantity }}</text>
                  </view>
                  <text class="price">¥{{ item.price * item.quantity }}</text>
                </view>
              </view>
            </view>

            <!-- 订单金额信息 -->
            <view class="detail-section">
              <view class="section-title">金额信息</view>
              <view class="amount-item">
                <text class="label">商品总额：</text>
                <text class="value">¥{{ currentOrder.total_amount }}</text>
              </view>
              <view class="amount-item" v-if="currentOrder.discount_amount > 0">
                <text class="label">优惠金额：</text>
                <text class="value">-¥{{ currentOrder.discount_amount }}</text>
              </view>
              <view class="amount-item total">
                <text class="label">实付金额：</text>
                <text class="value">¥{{ currentOrder.payable_amount }}</text>
              </view>
            </view>
          </template>
        </scroll-view>
      </view>
    </view>

    <!-- 支付方式选择弹窗 -->
    <view v-if="paymentMethodPopupVisible" class="modal">
      <view class="modal-mask" @tap="closePaymentMethodPopup"></view>
      <view class="payment-popup-wrapper">
        <view class="payment-method-popup" :animation="popupAnimation">
          <view class="popup-header">
            <text class="close-btn" @tap="closePaymentMethodPopup">×</text>
            <text class="title">选择支付方式</text>
          </view>
          <view class="method-list">
            <view class="method-item" @tap="selectPaymentMethod('wechat')">
              <image src="/static/tabbar/微信支付.png" class="method-icon wechat-icon"></image>
              <view class="method-info">
                <text class="method-name">微信支付</text>
                <text class="method-desc">推荐使用微信支付</text>
              </view>
              <text class="checkmark">✔</text>
            </view>
            <view class="method-item" @tap="selectPaymentMethod('member')">
              <image src="/static/tabbar/会员卡.png" class="method-icon member-icon"></image>
              <view class="method-info">
                <text class="method-name">会员卡支付</text>
                <text class="method-desc">使用会员卡余额支付</text>
              </view>
              <text class="checkmark">✔</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 会员卡支付提示弹窗 -->
    <view v-if="memberCardPopupVisible" class="modal">
      <view class="modal-mask" @tap="closeMemberCardPopup"></view>
      <view class="payment-popup-wrapper">
        <view class="member-card-popup" :animation="popupAnimation">
          <view class="popup-header">
            <text class="close-btn" @tap="closeMemberCardPopup">×</text>
            <text class="title">会员卡支付</text>
          </view>
          <view class="popup-content">
            <image src="/static/tabbar/会员卡.png" class="card-icon"></image>
            <view class="amount-info">
              <text class="amount-label">支付金额</text>
              <view class="amount-row">
                <text class="currency">¥</text>
                <text class="amount">{{ currentOrder?.payable_amount ? currentOrder.payable_amount.toFixed(2) : '0.00' }}</text>
              </view>
            </view>
          </view>
          <view class="popup-footer">
            <button class="confirm-btn" @tap="confirmMemberCardPayment">立即支付</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 支付选择弹窗 -->
    <view v-if="paymentPopupVisible" class="modal">
      <view class="modal-mask" @tap="closePaymentPopup"></view>
      <view class="payment-popup-wrapper">
        <view class="payment-popup" :animation="popupAnimation">
          <view class="popup-header">
            <text class="close-btn" @click="closePaymentPopup">×</text>
            <text class="password-btn">使用密码</text>
          </view>
          <view class="amount-section">
            <text class="merchant-name">商家名称</text>
            <view class="currency-amount-wrapper">
              <text class="currency">¥</text>
              <text class="amount">{{ currentOrder?.payable_amount ? currentOrder.payable_amount.toFixed(2) : '0.00' }}</text>
            </view>
          </view>
          <view class="divider-line"></view>
          <view class="payment-method-section">
            <view class="method-header">
              <view class="label">付款方式</view>
              <view class="change-method">
                <text>更改</text>
                <text class="arrow">></text>
              </view>
            </view>
            <view class="method-item">
              <image src="/static/tabbar/零钱通.png" class="method-icon"></image>
              <view class="method-details">
                <text class="method-name">零钱通</text>
                <text class="method-provider">由腾安公司提供货币基金销售服务</text>
              </view>
              <text class="checkmark">✔</text>
            </view>
          </view>
          <view class="popup-footer">
            <button class="pay-btn" @click="confirmPayment">支付</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 密码输入弹窗 -->
    <view v-if="passwordPopupVisible" class="modal">
      <view class="modal-mask" @tap="closePayPasswordPopup"></view>
      <view class="payment-popup-wrapper">
        <view class="pay-password-popup" :animation="popupAnimation">
          <view class="popup-header">
            <text class="close-btn" @tap="closePayPasswordPopup">×</text>
            <text class="face-btn">使用面容</text>
          </view>
          <view class="popup-amount">
            <text class="merchant">商家名称</text>
            <view class="currency-amount-row">
              <text class="currency">¥</text>
              <text class="amount">{{ currentOrder?.payable_amount ? currentOrder.payable_amount.toFixed(2) : '0.00' }}</text>
            </view>
          </view>
          <view class="popup-method">
            <view class="method-label">付款方式</view>
            <view class="method-change">
              <text>更改</text>
              <text class="arrow">></text>
            </view>
            <view class="method-item">
              <image src="/static/tabbar/建设银行.png" class="method-icon"></image>
              <view class="method-info">
                <text class="method-name">建设银行储蓄卡</text>
                <text class="method-desc">**** **** **** 2779</text>
              </view>
              <text class="checkmark">✔</text>
            </view>
          </view>
          <view class="popup-password">
            <view class="password-box">
              <view v-for="(cell, index) in 6" :key="index" class="pwd-cell">
                <view v-if="password.length > index" class="dot"></view>
              </view>
            </view>
          </view>
          <view class="popup-keyboard">
            <view v-for="(row, rowIndex) in keyboardRows" :key="rowIndex" class="keyboard-row">
              <view v-for="(key, keyIndex) in row" :key="keyIndex" :class="['key-btn', key === 'del' ? 'del' : (key === '' ? 'empty' : '')]" @click="onKeyClick(key)">{{ key }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 支付成功弹窗 -->
    <view v-if="successPopupVisible" class="modal">
      <view class="modal-mask" @tap="closePaySuccessPopup"></view>
      <view class="payment-popup-wrapper">
        <view class="pay-success-popup" :animation="popupAnimation">
          <view class="success-top-bar">
            <image src="/static/tabbar/微信支付.png" class="success-icon"></image>
            <text class="success-text">支付成功</text>
          </view>
          <view class="success-amount-block">
            <text class="success-merchant">商家名称</text>
            <view class="success-amount-row">
              <text class="currency">¥</text>
              <text class="amount">{{ currentOrder?.payable_amount ? currentOrder.payable_amount.toFixed(2) : '0.00' }}</text>
            </view>
          </view>
          <view class="success-bottom-block">
            <button class="success-btn" @tap="closePaySuccessPopup">完成</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { orderApi, payHistoryApi, userApi, boardApi } from '../../api/index'
import { couponApi } from '../../api/index'

// 定义标签页数据
const tabs = ['全部订单', '堂食订单', '外卖订单']
const currentTab = ref(0)

// 分页相关数据
const page = ref(1)
const pageSize = ref(10)
const loadMoreStatus = ref('loadmore') // loadmore, loading, nomore

// 用于存储订单展开状态的集合
const expandedOrders = ref(new Set())

// 订单数据
const orders = ref([])

// 当前查看的订单详情
const currentOrder = ref(null)
const showOrderDetail = ref(false)

// 支付选择弹窗
const paymentPopup = ref(null)
const paymentPopupVisible = ref(false)

// 密码输入弹窗
const password = ref('')
const passwordPopup = ref(null)
const passwordPopupVisible = ref(false)

// 支付成功弹窗
const successPopup = ref(null)
const successPopupVisible = ref(false)

// 数字键盘布局
const keyboardRows = [
  ['1', '2', '3'],
  ['4', '5', '6'],
  ['7', '8', '9'],
  ['', '0', 'del']
]

// 添加动画相关变量
const popupAnimation = ref(null)
const animation = ref(null)

// 添加新的状态变量
const paymentMethodPopupVisible = ref(false)
const memberCardPopupVisible = ref(false)

// 添加用户信息相关的状态
const userInfo = ref(null)
const usedCouponId = ref(null)

// 初始化动画实例
onMounted(() => {
  animation.value = uni.createAnimation({
    duration: 150,
    timingFunction: 'ease-out',
  })
})

// 支付弹窗状态变化
const paymentPopupChange = (e) => {
  if (!e.show) {
    paymentPopupVisible.value = false
  }
}

// 密码弹窗状态变化
const payPasswordPopupChange = (e) => {
  if (!e.show) {
    passwordPopupVisible.value = false
    password.value = ''
    // 如果不是要显示成功弹窗，则显示原生 tabBar
    if (!successPopupVisible.value) {
      uni.showTabBar()
    }
  }
}

// 添加一个检查弹窗状态的方法
const checkPopupStatus = () => {
  // 如果有任何一个弹窗显示，就隐藏 tabBar
  if (paymentMethodPopupVisible.value || 
      paymentPopupVisible.value || 
      passwordPopupVisible.value || 
      memberCardPopupVisible.value || 
      successPopupVisible.value) {
    uni.hideTabBar()
  } else {
    // 所有弹窗都关闭时，显示 tabBar
    uni.showTabBar()
  }
}

// 关闭支付弹窗
const closePaymentPopup = () => {
  // 执行滑出动画
  animation.value.translateY('100%').step()
  popupAnimation.value = animation.value.export()
  // 延迟关闭弹窗
  setTimeout(() => {
    paymentPopupVisible.value = false
    checkPopupStatus()
  }, 200)
}

// 关闭密码弹窗
const closePayPasswordPopup = () => {
  // 执行滑出动画
  animation.value.translateY('100%').step()
  popupAnimation.value = animation.value.export()
  // 延迟关闭弹窗
  setTimeout(() => {
    passwordPopupVisible.value = false
    password.value = ''  // 清空密码输入框
    checkPopupStatus()
  }, 200)
}

// 关闭成功弹窗
const closePaySuccessPopup = () => {
  // 执行滑出动画
  animation.value.translateY('100%').step()
  popupAnimation.value = animation.value.export()
  // 延迟关闭弹窗
  setTimeout(() => {
    successPopupVisible.value = false
    checkPopupStatus()
  }, 200)
}

// 处理键盘输入
const onKeyClick = (key) => {
  if (key === 'del') {
    if (password.value.length > 0) {
      password.value = password.value.slice(0, -1)
    }
  } else if (key && password.value.length < 6) {
    password.value += key
    if (password.value.length === 6) {
      verifyPassword()
    }
  }
}

// 验证密码
const verifyPassword = async () => {
  try {
    uni.showLoading({ title: '验证中...' })
    if (!userInfo.value) {
      throw new Error('请先登录')
    }
    
    // 构建支付记录数据
    const payHistory = {
      order_id: currentOrder.value.order_id,
      u_id: userInfo.value.uId,  // 改用 uId 字段
      pay_amount: currentOrder.value.payable_amount,
      pay_way: 1  // 1表示会员卡支付
    }
    
    // 发送添加支付记录请求
    const token = uni.getStorageSync('token')
    const res = await payHistoryApi.addPayHistory(token, payHistory)
    
    if (res.code !== 200) {
      throw new Error(res.msg || '支付失败')
    }

    // 立即获取订单详情并修改餐桌状态
    try {
      console.log('准备获取订单详情', currentOrder.value.order_id)
      const orderDetailRes = await orderApi.getOrderDetail(currentOrder.value.order_id)
      console.log('订单详情返回：', orderDetailRes)
      if (orderDetailRes.code === 200 && orderDetailRes.data && orderDetailRes.data.boardId) {
        console.log('准备修改餐桌状态，boardId:', orderDetailRes.data.boardId)
        await boardApi.updBoard({ boardId: orderDetailRes.data.boardId, boardStatus: 0 })
        console.log('修改餐桌状态请求已发送')
      } else {
        console.warn('未找到餐桌ID，无法修改餐桌状态')
      }
    } catch (err) {
      uni.showToast({ title: '餐桌状态修改失败', icon: 'none' })
      console.error('修改餐桌状态异常', err)
    }

    setTimeout(() => {
      uni.hideLoading()
      closePayPasswordPopup()
      successPopupVisible.value = true
      nextTick(() => {
        animation.value.translateY(0).step()
        popupAnimation.value = animation.value.export()
        checkPopupStatus()
        
        // 添加调试信息
        console.log('当前订单信息：', currentOrder.value)
        console.log('订单优惠金额：', currentOrder.value.discount_amount)
        console.log('优惠金额类型：', typeof currentOrder.value.discount_amount)
        
        // 确保优惠金额是数字类型
        const discountAmount = parseFloat(currentOrder.value.discount_amount) || 0
        console.log('转换后的优惠金额：', discountAmount)
        console.log('优惠金额是否大于0：', discountAmount > 0)
        
        // 如果订单有优惠金额（大于0），调用优惠券使用接口
        if (discountAmount > 0) {
          console.log('准备调用优惠券扣除接口')
          // 这里需要根据实际情况获取优惠券ID，暂时使用usedCouponId
          const couponId = usedCouponId.value || 1 // 如果没有设置usedCouponId，使用默认值1
          console.log('使用的优惠券ID：', couponId)
          console.log('用户ID：', userInfo.value.uId)
          
          couponApi.useCoupon(userInfo.value.uId, couponId)
            .then(res => {
              console.log('优惠券使用成功：', res)
            })
            .catch(err => {
              console.error('优惠券使用失败：', err)
            })
        } else {
          console.log('订单没有优惠金额，跳过优惠券扣除')
        }
        
        // 支付成功后延迟刷新页面
        setTimeout(() => {
          // 重新获取用户信息
          getUserInfo()
          // 重新获取订单列表
          getOrders()
          // 重置分页数据
          page.value = 1
          loadMoreStatus.value = 'loadmore'
        }, 500)
      })
    }, 1000)

  } catch (error) {
    uni.hideLoading()
    uni.showToast({ 
      title: error.message || '支付失败，请稍后重试', 
      icon: 'none',
      duration: 2000
    })
    // 关闭密码输入弹窗
    closePayPasswordPopup()
    checkPopupStatus()
    // 如果是未登录错误，跳转到登录页
    if (error.message === '请先登录') {
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/index'
        })
      }, 1500)
    }
  }
}

// 支付弹窗内点击支付，弹出密码输入弹窗
const confirmPayment = () => {
  // 先隐藏原生 tabBar
  uni.hideTabBar()
  closePaymentPopup()
  passwordPopupVisible.value = true
  // 执行滑入动画
  nextTick(() => {
    animation.value.translateY(0).step()
    popupAnimation.value = animation.value.export()
    checkPopupStatus()
  })
}

// 支付订单
const payOrder = (orderId) => {
  // 找到对应的订单信息
  const order = orders.value.find(order => order.order_id === orderId)
  if (!order) return
  
  // 设置当前订单信息
  currentOrder.value = order
  // 显示支付方式选择弹窗
  paymentMethodPopupVisible.value = true
  // 执行滑入动画
  nextTick(() => {
    animation.value.translateY(0).step()
    popupAnimation.value = animation.value.export()
    checkPopupStatus()
  })
}

// 获取订单数据
const getOrders = async () => {
  try {
    const token = uni.getStorageSync('token')
    const res = await orderApi.getOrderList(token)
    
    if (res.code === 200) {
      // 处理数据，将相同订单编号的数据合并
      const orderMap = new Map()
      res.data.forEach(item => {
        if (!orderMap.has(item.订单编号)) {
          orderMap.set(item.订单编号, {
            order_id: item.订单编号,                    // Integer 订单编号
            order_type: item.订单类型 === '堂食' ? 1 : 2,  // String 订单类型
            board_name: item.餐桌名称,                   // String 餐桌名称
            order_status: item.订单状态 === '已支付' ? 0 : 1, // String 订单状态
            place_order_time: new Date(item.下单时间).toLocaleString(), // Date 下单时间
            total_amount: item.总计金额,                 // BigDecimal 总计金额
            discount_amount: item.优惠金额,              // BigDecimal 优惠金额
            payable_amount: item.实付金额,               // BigDecimal 实付金额
            items: []
          })
        }
        const orderItem = {
          item_id: item.订单编号,        // Integer 订单编号
          dish_name: item.菜品名称,      // String 菜品名称
          dish_image: item.菜品图片,     // String 菜品图片
          quantity: item.菜品数量,       // Integer 菜品数量
          price: item.单价,             // BigDecimal 单价
          subtotal: item.小计           // BigDecimal 小计
        }
        orderMap.get(item.订单编号).items.push(orderItem)
      })
      
      // 根据当前选中的标签过滤订单
      const allOrders = Array.from(orderMap.values())
      
      if (currentTab.value === 1) { // 堂食订单
        orders.value = allOrders.filter(order => order.order_type === 1)
      } else if (currentTab.value === 2) { // 外卖订单
        orders.value = allOrders.filter(order => order.order_type === 2)
      } else { // 全部订单
        orders.value = allOrders
      }
    } else {
      orders.value = []
      uni.showToast({
        title: res.msg || '获取订单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取订单失败：', error)
    orders.value = []
    uni.showToast({
      title: '获取订单失败',
      icon: 'none'
    })
  }
}

// 页面加载时初始化数据
onMounted(() => {
  getUserInfo()  // 直接从本地存储获取用户信息
  getOrders()
  // 初始化加载更多
  loadMore()
})

/**
 * 切换订单的展开/收起状态
 * @param {number} orderId - 订单ID
 */
const toggleExpand = (orderId) => {
  if (expandedOrders.value.has(orderId)) {
    expandedOrders.value.delete(orderId)  // 如果已展开则收起
  } else {
    expandedOrders.value.add(orderId)     // 如果已收起则展开
  }
}

/**
 * 检查订单是否处于展开状态
 * @param {number} orderId - 订单ID
 * @returns {boolean} - 是否展开
 */
const isExpanded = (orderId) => {
  return expandedOrders.value.has(orderId)
}

/**
 * 获取应该显示的订单项列表
 * @param {Object} order - 订单对象
 * @returns {Array} - 应该显示的订单项列表
 */
const getVisibleItems = (order) => {
  if (!order || !order.items) {
    return []
  }
  
  if (isExpanded(order.order_id)) {
    return order.items  // 如果已展开，返回所有商品
  }
  return order.items.slice(0, 1)  // 如果已收起，只返回第一个商品
}

/**
 * 获取订单状态的显示文本
 * @param {number} status - 订单状态码
 * @returns {string} - 状态显示文本
 */
const getOrderStatus = (status) => {
  return status === 0 ? '已支付' : '待支付'
}

/**
 * 格式化时间显示
 * @param {string} time - 时间字符串
 * @returns {string} - 格式化后的时间字符串
 */
const formatTime = (time) => {
  return time
}

/**
 * 加载更多订单
 */
const loadMore = async () => {
  if (loadMoreStatus.value === 'loading' || loadMoreStatus.value === 'nomore') return
  
  loadMoreStatus.value = 'loading'
  try {
    // 模拟异步加载数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 如果只有两条数据，直接设置为没有更多
    if (orders.value.length <= 2) {
      loadMoreStatus.value = 'nomore'
      return
    }
    
    // 这里应该是实际的API调用
    // const res = await getOrders({ page: page.value, pageSize: pageSize.value })
    
    page.value++
    loadMoreStatus.value = 'nomore' // 由于目前只有两条数据，直接设置为没有更多
  } catch (error) {
    console.error('加载订单失败:', error)
    loadMoreStatus.value = 'loadmore'
  }
}

// 页面触底事件
const onReachBottom = () => {
  loadMore()
}

/**
 * 处理标签页切换
 * @param {number} index - 标签页索引
 */
const handleTabChange = (index) => {
  currentTab.value = index
  // 重置分页数据
  page.value = 1
  loadMoreStatus.value = 'loadmore'
  // 这里应该重新加载对应标签的订单数据
  // 重新获取订单数据
  getOrders()
}

/**
 * 跳转到点单页面
 */
const goToOrder = () => {
  uni.switchTab({
    url: '../member/index'
  })
}

/**
 * 取消订单
 * @param {number} orderId - 订单ID
 */
const cancelOrder = (orderId) => {
  // 实现取消订单逻辑
}

/**
 * 继续加菜（仅堂食订单）
 * @param {number} orderId - 订单ID
 */
const addMoreDishes = (orderId) => {
  // 跳转到点餐页面，并携带订单ID
  uni.navigateTo({
    url: `/pages/menu/index?orderId=${orderId}`
  })
}

/**
 * 查看订单详情
 * @param {number} orderId - 订单ID
 */
const viewOrderDetail = (orderId) => {
  // 找到对应的订单信息
  currentOrder.value = orders.value.find(order => order.order_id === orderId)
  // 显示弹窗
  showOrderDetail.value = true
}

/**
 * 关闭订单详情弹窗
 */
const closeOrderDetail = () => {
  showOrderDetail.value = false
  currentOrder.value = null
}

// 支付成功弹窗状态变化
const paySuccessPopupChange = (e) => {
  if (!e.show) {
    successPopupVisible.value = false
    // 显示原生 tabBar
    uni.showTabBar()
  }
}

// 关闭支付方式选择弹窗
const closePaymentMethodPopup = () => {
  // 执行滑出动画
  animation.value.translateY('100%').step()
  popupAnimation.value = animation.value.export()
  // 延迟关闭弹窗
  setTimeout(() => {
    paymentMethodPopupVisible.value = false
    checkPopupStatus()
  }, 200)
}

// 选择支付方式
const selectPaymentMethod = (method) => {
  closePaymentMethodPopup()
  if (method === 'wechat') {
    // 显示支付选择弹窗
    paymentPopupVisible.value = true
    // 执行滑入动画
    nextTick(() => {
      animation.value.translateY(0).step()
      popupAnimation.value = animation.value.export()
      checkPopupStatus()
    })
  } else if (method === 'member') {
    // 显示会员卡支付确认弹窗
    memberCardPopupVisible.value = true
    // 执行滑入动画
    nextTick(() => {
      animation.value.translateY(0).step()
      popupAnimation.value = animation.value.export()
      checkPopupStatus()
    })
  }
}

// 关闭会员卡支付提示弹窗
const closeMemberCardPopup = () => {
  // 执行滑出动画
  animation.value.translateY('100%').step()
  popupAnimation.value = animation.value.export()
  // 延迟关闭弹窗
  setTimeout(() => {
    memberCardPopupVisible.value = false
    checkPopupStatus()
  }, 200)
}

// 确认会员卡支付
const confirmMemberCardPayment = () => {
  closeMemberCardPopup()
  handleMemberCardPayment()
}

// 处理会员卡支付
const handleMemberCardPayment = async () => {
  try {
    // 打印用户信息，看看具体是什么
    console.log('当前用户信息：', userInfo.value)
    console.log('用户信息类型：', typeof userInfo.value)
    console.log('用户信息字符串：', JSON.stringify(userInfo.value))
    
    // 构建支付记录数据
    const payHistory = {
      order_id: currentOrder.value.order_id,
      u_id: userInfo.value.uId,  // 改用 uId 字段
      pay_amount: currentOrder.value.payable_amount,
      pay_way: 1  // 1表示会员卡支付
    }
    
    // 打印支付数据
    console.log('支付数据：', payHistory)
    
    uni.showLoading({ title: '支付中...' })
    if (!userInfo.value) {
      throw new Error('请先登录')
    }
    
    // 发送添加支付记录请求
    const token = uni.getStorageSync('token')
    const res = await payHistoryApi.addPayHistory(token, payHistory)
    
    if (res.code !== 200) {
      throw new Error(res.msg || '支付失败')
    }

    // 立即获取订单详情并修改餐桌状态
    try {
      console.log('准备获取订单详情', currentOrder.value.order_id)
      const orderDetailRes = await orderApi.updOrder(currentOrder.value.order_id)
      console.log('订单详情返回：', orderDetailRes)
      if (orderDetailRes.code === 200 && orderDetailRes.data && orderDetailRes.data.boardId) {
        console.log('准备修改餐桌状态，boardId:', orderDetailRes.data.boardId)
        await boardApi.updBoard({ boardId: orderDetailRes.data.boardId, boardStatus: 0 })
        console.log('修改餐桌状态请求已发送')
      } else {
        console.warn('未找到餐桌ID，无法修改餐桌状态')
      }
    } catch (err) {
      uni.showToast({ title: '餐桌状态修改失败', icon: 'none' })
      console.error('修改餐桌状态异常', err)
    }

    // 支付成功
    setTimeout(async () => {
      uni.hideLoading()
      
      // 添加调试信息
      console.log('会员卡支付 - 当前订单信息：', currentOrder.value)
      console.log('会员卡支付 - 订单优惠金额：', currentOrder.value.discount_amount)
      console.log('会员卡支付 - 优惠金额类型：', typeof currentOrder.value.discount_amount)
      console.log('会员卡支付 - 优惠金额是否大于0：', currentOrder.value.discount_amount > 0)
      
      // 确保优惠金额是数字类型
      const discountAmount = parseFloat(currentOrder.value.discount_amount) || 0
      console.log('转换后的优惠金额：', discountAmount)
      console.log('优惠金额是否大于0：', discountAmount > 0)
      
      // 如果订单有优惠金额（大于0），调用优惠券使用接口
      if (discountAmount > 0) {
        console.log('会员卡支付 - 准备调用优惠券扣除接口')
        // 这里需要根据实际情况获取优惠券ID，暂时使用usedCouponId
        const couponId = usedCouponId.value || 1 // 如果没有设置usedCouponId，使用默认值1
        console.log('会员卡支付 - 使用的优惠券ID：', couponId)
        console.log('会员卡支付 - 用户ID：', userInfo.value.uId)
        
        couponApi.useCoupon(userInfo.value.uId, couponId)
          .then(res => {
            console.log('会员卡支付 - 优惠券使用成功：', res)
          })
          .catch(err => {
            console.error('会员卡支付 - 优惠券使用失败：', err)
          })
      } else {
        console.log('会员卡支付 - 订单没有优惠金额，跳过优惠券扣除')
      }
      
      // 显示支付成功提示
      uni.showToast({
        title: '支付成功',
        icon: 'success',
        duration: 2000
      })
      // 刷新页面
      setTimeout(() => {
        // 重新获取用户信息
        getUserInfo()
        // 重新获取订单列表
        getOrders()
        // 重置分页数据
        page.value = 1
        loadMoreStatus.value = 'loadmore'
      }, 500)
    }, 1000)

  } catch (error) {
    uni.hideLoading()
    uni.showToast({ 
      title: error.message || '支付失败，请稍后重试', 
      icon: 'none',
      duration: 2000
    })
    // 如果是未登录错误，跳转到登录页
    if (error.message === '请先登录') {
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/index'
        })
      }, 1500)
    }
  }
}

// 添加获取用户信息的方法
const getUserInfo = () => {
  try {
    // 直接从本地存储获取用户信息
    const storedUserInfo = uni.getStorageSync('userInfo')
    if (!storedUserInfo) {
      throw new Error('请先登录')
    }
    userInfo.value = storedUserInfo
  } catch (error) {
    uni.showToast({
      title: error.message || '获取用户信息失败',
      icon: 'none'
    })
    // 跳转到登录页
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/index'
      })
    }, 1500)
  }
}

// 设置使用的优惠券ID
const setUsedCoupon = (couponId) => {
  usedCouponId.value = couponId
}

// 清除使用的优惠券ID
const clearUsedCoupon = () => {
  usedCouponId.value = null
}
</script>

<style lang="scss" scoped>
.order {
  min-height: 100vh;
  background-color: #f5f5f5;
  // 支付弹窗样式
  .modal {
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    z-index: 999;
    
    .modal-mask {
      position: absolute;
      top: 0; left: 0; right: 0; bottom: 0;
      background-color: rgba(0, 0, 0, 0.6);
      backdrop-filter: blur(1px);
    }
    
    .payment-popup-wrapper {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      z-index: 1000;
    }
    
    .payment-popup {
      width: 100%;
      background-color: #ffffff;
      border-top-left-radius: 20rpx;
      border-top-right-radius: 20rpx;
      padding-bottom: constant(safe-area-inset-bottom);
      padding-bottom: env(safe-area-inset-bottom);
      transform: translateY(100%);
    }
  }
  
  // 其他样式（如 popup-header、amount-section、divider-line、payment-method-section、popup-footer 等）保持不变
  .payment-popup { /* 弹窗样式（内部样式） */
		.popup-header { display: flex; justify-content: space-between; align-items: center; padding: 10rpx 30rpx 20rpx; .close-btn { font-size: 40px; color: #999; } .password-btn { font-size: 28rpx; color: #687597; } }
		.amount-section { display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 10rpx 0; .merchant-name { font-size: 28rpx; color: #888; margin-bottom: 20rpx; } .currency-amount-wrapper { display: flex; align-items: flex-end; .currency { font-size: 48rpx; font-weight: bold; color: #333; position: relative; top: -35rpx; } .amount { font-size: 80rpx; font-weight: bold; color: #333; margin-left: 10rpx; } } }
		.divider-line { height: 1rpx; background-color: #eee; margin: 20rpx 0; }
		.payment-method-section { padding: 0 30rpx; margin-bottom: 40rpx; .method-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20rpx; .label { font-size: 26rpx; color: #999; } .change-method { display: flex; align-items: center; font-size: 26rpx; color: #999; .arrow { margin-left: 10rpx; font-weight: bold; } } } .method-item { display: flex; align-items: center; background: #FFF8E6; border-radius: 12rpx; padding: 40rpx 30rpx; position: relative; .method-icon { width: 25rpx; height: 25rpx; margin-right: 20rpx; position: relative; top: -7px; } .method-details { flex: 1; display: flex; flex-direction: column; justify-content: center; .method-name { font-size: 26rpx; color: #888; margin-bottom: 10px; } .method-provider { font-size: 22rpx; color: #888; } } .checkmark { font-size: 36rpx; color: #07c160; margin-left: 20rpx; position: relative; left: -10px; } } }
		.popup-footer { padding: 20rpx 30rpx; .pay-btn { background-color: #07c160; color: #ffffff; font-size: 32rpx; height: 90rpx; line-height: 90rpx; border-radius: 20rpx; width: 50%; margin-top: 20px; margin-bottom: 20px; } }
  }

  // 密码输入弹窗样式
	.pay-password-popup {
		background: #fff;
		border-top-left-radius: 32rpx;
		border-top-right-radius: 32rpx;
		padding-bottom: env(safe-area-inset-bottom);
		box-shadow: 0 -8rpx 32rpx rgba(0,0,0,0.08);
		position: fixed;
		bottom: -33px;
    width: 100%;
		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 15rpx 32rpx 0 32rpx;
			.close-btn {
				font-size: 40px;
				color: #333;
			}
			.face-btn {
				font-size: 28rpx;
				color: #576b95;
			}
		}
		.popup-amount {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-top: 16rpx;
			.merchant {
				font-size: 28rpx;
				color: #888;
				margin-bottom: 8rpx;
			}
			.currency-amount-row {
				display: flex;
				align-items: baseline;
				justify-content: center;
				.currency {
					font-size: 22px;
					font-weight: 600;
					color: #222;
					margin-right: 2px;
					position: relative;
					top: -2px;
				}
				.amount {
					font-size: 40px;
					font-weight: 600;
					color: #222;
					line-height: 1;
				}
			}
		}
		.popup-method {
			margin: 0 32rpx 24rpx 32rpx;
			.method-label {
				font-size: 24rpx;
				color: #999;
				margin-bottom: 8rpx;
			}
			.method-change {
				position: absolute;
				right: 48rpx;
				top: 0;
				font-size: 24rpx;
				color: #999;
				.arrow { margin-left: 4rpx; }
			}
			.method-item {
				display: flex;
				align-items: center;
				background: #EAF3FC;
				border-radius: 16rpx;
				padding: 37rpx 20rpx;
				margin-top: 25rpx;
				.method-icon {
					width: 50rpx;
					height: 40rpx;
					margin-right: 16rpx;
				}
				.method-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					.method-name {
						font-size: 28rpx;
						color: #333;
					}
					.method-desc {
						font-size: 22rpx;
						color: #888;
					}
				}
				.checkmark {
					font-size: 36rpx;
					color: #07c160;
					margin-left: 12rpx;
				}
			}
			position: relative;
		}
		.popup-password {
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 32rpx 0 0 0;
			.password-box {
				display: flex;
				gap: 16rpx;
				.pwd-cell {
					width: 74rpx;
					height: 74rpx;
					border-radius: 8rpx;
					background: #F2F2F2;
					display: flex;
					align-items: center;
					justify-content: center;
					margin: 10px 0px;
					.dot {
						width: 16rpx;
						height: 16rpx;
						background: #222;
						border-radius: 50%;
					}
				}
			}
		}
		.popup-keyboard {
			background: #EDEDED;
			padding-bottom: env(safe-area-inset-bottom);
			margin-top: 10px;
			border-top: 1px solid #EDEDED;
			.keyboard-row {
				display: flex;
				width: 100%;
				.key-btn {
					flex: 1;
					height: 55px;
					background: #fff;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 28px;
					color: #222;
					border-right: 1px solid #e5e5e5;
					border-bottom: 1px solid #e5e5e5;
					box-sizing: border-box;
					border-radius: 0;
					&.del {
						background: #EDEDED;
						color: #222;
					}
					&.empty {
						background: #EDEDED;
						border-right: none;
						border-bottom: none;
					}
				}
				.key-btn:last-child {
					border-right: none;
				}
			}
			.keyboard-row:last-child .key-btn {
				border-bottom: none;
			}
		}
	}

	// 支付成功全屏弹窗样式
	.pay-success-popup {
		position: fixed;
		left: 0; right: 0; top: 0; bottom: 0;
		width: 100vw; height: 100vh;
		background: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-start;
		z-index: 9999;
		.success-top-bar {
			margin-top: 25px;
			margin-bottom: 50px;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			.success-icon {
				width: 20px;
				height: 20px;
				margin-bottom: 0;
			}
			.success-text {
				color: #07c160;
				font-size: 15px;
				font-weight: 500;
				margin-left: 8px;
				margin-bottom: 0;
			}
		}
		.success-amount-block {
			margin-top: 16px;
			display: flex;
			flex-direction: column;
			align-items: center;
			.success-merchant {
				color: #888;
				font-size: 15px;
				margin-bottom: 10px;
			}
			.success-amount-row {
				display: flex;
				align-items: baseline;
				justify-content: center;
				.currency {
					font-size: 30px;
					font-weight: 600;
					color: #222;
					margin-right: 2px;
					position: relative;
					top: -9px;
				}
				.amount {
					font-size: 40px;
					font-weight: 600;
					color: #222;
					line-height: 1;
				}
			}
		}
		.success-progress {
			width: 80vw;
			margin: 32px 0 48px 0;
			display: flex;
			justify-content: center;
			.progress-bar {
				width: 100%;
				height: 6px;
				background: #f5f5f5;
				border-radius: 3px;
				overflow: hidden;
				.progress-inner {
					width: 30px;
					height: 100%;
					background: #fa5151;
					border-radius: 3px;
				}
			}
		}
		.success-bottom-block {
			width: 100vw;
			display: flex;
			flex-direction: column;
			align-items: center;
			position: absolute;
			bottom: 60px;
			left: 0;
			.success-btn {
				position: relative;
				top: -40px;
				width: 40vw;
				height: 44px;
				background: #f5f5f5;
				color: #222;
				font-size: 15px;
				border-radius: 5px;
				border: none;
				margin: 0 auto;
				text-align: center;
				line-height: 44px;
			}
		}
	}

  // 支付方式选择弹窗样式
  .payment-method-popup {
    width: 100%;
    background: #fff;
    border-top-left-radius: 32rpx;
    border-top-right-radius: 32rpx;
    padding-bottom: env(safe-area-inset-bottom);
    box-shadow: 0 -8rpx 32rpx rgba(0,0,0,0.08);
    transform: translateY(100%);

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx;
      .close-btn {
        font-size: 40px;
        color: #333;
      }
      .title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
      }
    }

    .method-list {
      padding: 0 32rpx;
      .method-item {
        display: flex;
        align-items: center;
        padding: 32rpx 0;
        border-bottom: 1px solid #f5f5f5;
        &:last-child {
          border-bottom: none;
        }
        .method-icon {
          width: 40rpx;
          height: 40rpx;
          margin-right: 24rpx;
          &.wechat-icon {
            width: 44rpx;
            height: 44rpx;
          }
          &.member-icon {
            width: 48rpx;
            height: 48rpx;
          }
        }
        .method-info {
          flex: 1;
          .method-name {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 8rpx;
          }
          .method-desc {
            font-size: 24rpx;
            color: #999;
          }
        }
        .checkmark {
          font-size: 36rpx;
          color: #07c160;
          margin-left: 24rpx;
        }
      }
    }
  }

  // 会员卡支付提示弹窗样式
  .member-card-popup {
    width: 100%;
    background: #fff;
    border-top-left-radius: 32rpx;
    border-top-right-radius: 32rpx;
    padding-bottom: env(safe-area-inset-bottom);
    box-shadow: 0 -8rpx 32rpx rgba(0,0,0,0.08);
    transform: translateY(100%);

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx;
      .close-btn {
        font-size: 40px;
        color: #333;
      }
      .title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
      }
    }

    .popup-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 48rpx 32rpx;
      .card-icon {
        width: 96rpx;
        height: 96rpx;
        margin-bottom: 32rpx;
      }
      .amount-info {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-bottom: 32rpx;
        .amount-label {
          font-size: 28rpx;
          color: #999;
          margin-bottom: 16rpx;
        }
        .amount-row {
          display: flex;
          align-items: baseline;
          .currency {
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
            margin-right: 4rpx;
            position: relative;
            top: -4rpx;
          }
          .amount {
            font-size: 48rpx;
            font-weight: 600;
            color: #333;
          }
        }
      }
      .tip-text {
        font-size: 32rpx;
        color: #333;
        margin-bottom: 16rpx;
      }
      .sub-tip {
        font-size: 28rpx;
        color: #999;
      }
    }

    .popup-footer {
      padding: 32rpx;
      .confirm-btn {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        background: #07c160;
        color: #fff;
        font-size: 32rpx;
        border-radius: 44rpx;
        border: none;
      }
    }
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 44rpx 32rpx;
  font-size: 36rpx;
  font-weight: 500;

  .more {
    font-size: 40rpx;
  }
}

.tabs {
  display: flex;
  justify-content: space-around;
  padding: 0 32rpx;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;

  .tab-item {
    position: relative;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #666;

    &.active {
      color: #333;
      font-weight: 500;
    }

    .active-line {
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 4rpx;
      background-color: #ff6b35;
      border-radius: 2rpx;
    }
  }
}

.order-list {
  padding: 20rpx;
}

.order-item {
  margin-bottom: 20rpx;
  padding: 24rpx;
  background-color: #fff;
  border-radius: 12rpx;

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;

    .shop-info {
      display: flex;
      align-items: center;
      
      .tag {
        padding: 4rpx 12rpx;
        margin-right: 12rpx;
        font-size: 24rpx;
        color: #ff6b35;
        background-color: #fff5f0;
        border-radius: 4rpx;
      }

      .shop-name {
        font-size: 28rpx;
        color: #333;
      }
    }

    .status {
      font-size: 26rpx;
      color: #999;
    }
  }

  .order-time {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 16rpx;
  }

  .order-content {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-top: 1px solid #f5f5f5;

    &:last-of-type {
      border-bottom: 1px solid #f5f5f5;
    }

    .product-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
      flex-shrink: 0;
    }

    .product-info {
      flex: 1;
      margin-right: 20rpx;
      min-width: 0;
      word-break: break-all;
      
      .product-name {
        font-size: 26rpx;
        color: #333;
        margin-bottom: 8rpx;
        font-weight: 500;
        word-break: break-all;
      }

      .product-meta {
        font-size: 24rpx;
        color: #999;

        .count {
          font-size: 24rpx;
          color: #999;
          background: #f8f8f8;
          padding: 4rpx 12rpx;
          border-radius: 6rpx;
          display: inline-block;
          margin-left: 10rpx;
        }
      }
    }

    .price {
      font-size: 26rpx;
      color: #ff6b35;
      font-weight: 600;
      flex-shrink: 0;
      margin-left: 20rpx;
      word-break: break-all;
      text-align: right;
    }
  }

  .order-footer {
    padding: 20rpx 0;
    text-align: right;
    font-size: 26rpx;

    .amount-info {
      color: #666;
      margin-bottom: 8rpx;

      .total-amount {
        font-weight: 500;
        color: #333;
      }

      .discount {
        color: #ff6b35;
        margin-left: 8rpx;
      }
    }

    .payable-amount {
      color: #ff6b35;
      font-size: 32rpx;
      font-weight: 500;
    }
  }

  .order-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 20rpx;
    gap: 16rpx;

    .action-btn {
      padding: 0 32rpx;
      height: 56rpx;
      line-height: 56rpx;
      font-size: 24rpx;
      color: #666;
      background-color: #fff;
      border: 1px solid #ddd;
      border-radius: 28rpx;

      &.primary {
        color: #ff6b35;
        border-color: #ff6b35;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 160rpx;

  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 32rpx;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 48rpx;
  }

  .order-btn {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #0593d3;
    color: #fff;
    font-size: 28rpx;
    border-radius: 40rpx;
    border: none;
    margin: 0 auto;
    font-weight: 500;
    letter-spacing: 2rpx;
    box-shadow: none;
    display: block;
  }
}

.expand-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 0;
  font-size: 24rpx;
  color: #666;
  border-bottom: 1px solid #f5f5f5;
  
  .expand-icon {
    display: inline-block;
    margin-left: 8rpx;
    transition: transform 0.3s ease;
    transform: rotate(90deg);
    
    &.is-expanded {
      transform: rotate(-90deg);
    }
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  
  .modal-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
    backdrop-filter: blur(4px);
  }
  
  .order-detail-popup {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 650rpx;
    max-height: 85vh;
    background-color: #fff;
    border-radius: 24rpx;
    overflow: hidden;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx;
      background: linear-gradient(to right, #ff6b35, #ff8c35);
      
      .title {
        font-size: 36rpx;
        font-weight: 600;
        color: #fff;
      }
      
      .close-btn {
        font-size: 48rpx;
        color: rgba(255, 255, 255, 0.9);
        padding: 0 20rpx;
        line-height: 1;
      }
    }
    
    .popup-content {
      max-height: calc(85vh - 100rpx);
      padding: 32rpx;
      
      .detail-section {
        margin-bottom: 40rpx;
        background: #fff;
        border-radius: 16rpx;
        padding: 24rpx;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
        
        .section-title {
          font-size: 28rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 24rpx;
          padding-left: 16rpx;
          border-left: 6rpx solid #ff6b35;
        }
      }
      
      .info-item {
        display: flex;
        margin-bottom: 16rpx;
        font-size: 26rpx;
        
        .label {
          color: #666;
          width: 140rpx;
          flex-shrink: 0;
        }
        
        .value {
          color: #333;
          flex: 1;
          font-weight: 500;
          word-break: break-all;
        }
      }
      
      .product-list {
        .product-item {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          padding: 20rpx 0;
          border-bottom: 1px solid #f5f5f5;
          
          &:last-child {
            border-bottom: none;
          }
          
          .product-info {
            flex: 1;
            margin-right: 20rpx;
            max-width: 60%;
            
            .name {
              font-size: 26rpx;
              color: #333;
              margin-bottom: 8rpx;
              font-weight: 500;
            }
            
            .quantity {
              font-size: 24rpx;
              color: #999;
              background: #f8f8f8;
              padding: 4rpx 12rpx;
              border-radius: 6rpx;
              display: inline-block;
            }
          }
          
          .price {
            font-size: 26rpx;
            color: #ff6b35;
            font-weight: 600;
            flex-shrink: 0;
            min-width: 120rpx;
            text-align: right;
            margin-left: 20rpx;
          }
        }
      }
      
      .amount-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;
        font-size: 26rpx;
        
        &.total {
          margin-top: 24rpx;
          padding-top: 24rpx;
          border-top: 2rpx solid #f5f5f5;
          font-size: 28rpx;
          font-weight: 600;
          
          .value {
            color: #ff6b35;
            margin-left: auto;
          }
        }
        
        .label {
          color: #666;
          flex-shrink: 0;
          margin-right: 20rpx;
        }
        
        .value {
          color: #333;
          flex: 1;
          font-weight: 500;
          word-break: break-all;
        }
      }
    }
  }
}
</style>